<template>
  <div class="menu-permission">
    <el-card class="permission-card">
      <template #header>
        <div class="card-header">
          <span class="title">菜单权限分配</span>
        </div>
      </template>

      <!-- 角色选择按钮组 -->
      <div class="role-tabs">
        <el-tabs 
          v-model="activeTab"
          @tab-click="handleTabClick"
          type="border-card"
        >
          <el-tab-pane
            v-for="role in roleList"
            :key="role.id"
            :label="role.roleName"
            :name="role.id.toString()"
          >
            <template #label>
              <span :class="['role-label', getRoleClass(role)]">{{ role.roleName }}</span>
            </template>
            <!-- 菜单权限表格 -->
            <el-table
              v-if="menuList.length > 0"
              :data="menuList"
              row-key="id"
              border
              class="menu-table"
              :tree-props="{ children: 'children', indent: 16 }"
            >
              <el-table-column label="菜单名称" min-width="200">
                <template #default="{ row }">
                  <div class="menu-cell">
                    <span>{{ row.name }}</span>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="perms" label="权限标识" min-width="200" />

              <el-table-column label="访问权限" width="120" align="center">
                <template #default="{ row }">
                  <el-checkbox
                    v-model="row.checked"
                    :disabled="shouldDisableMenu(row)" 
                    @change="(val: boolean) => handlePermissionChange(row, val)"
                  />
                </template>
              </el-table-column>
            </el-table>
            <div v-else class="no-data">
              暂无菜单数据
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 保存按钮 -->
      <div class="action-bar" v-if="selectedRole">
        <el-button type="primary" :loading="loading" @click="handleSave">保存修改</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { getMenuTree } from '@/api/menu'
import { getRoleList, getRoleMenus, updateRoleMenus } from '@/api/role'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const store = useStore()
const loading = ref(false)
const activeTab = ref('')
const selectedRole = ref<number>()
const roleList = ref<Role[]>([])
const menuList = ref<any[]>([])

interface Role {
  id: number
  roleKey: string
  roleName: string
}

// 判断是否是超级管理员
const isSuperAdmin = (roleId: number) => {
  const role = roleList.value.find(r => r.id === roleId)
  return role?.roleKey === 'superadmin'
}

// 判断是否是管理员
const isAdmin = computed(() => {
  return store.state.user.role === 'admin'
})

// 判断是否可以管理该角色
const canManageRole = (role: Role) => {
  if (isSuperAdmin(store.state.user.roleId)) return true
  if (isAdmin.value && role.roleKey !== 'superadmin') return true
  return false
}

// 判断是否可以管理该菜单
const canManageMenu = (menu: any) => {
  if (isSuperAdmin(store.state.user.roleId)) return true
  if (isAdmin.value && !menu.superAdminOnly) return true
  return false
}

// 判断是否应该禁用菜单
const shouldDisableMenu = (menu: any) => {
  // 只有超级管理员的系统管理相关菜单需要禁用
  if (selectedRole.value && isSuperAdmin(selectedRole.value)) {
    // 系统管理本身或其子菜单都禁用
    if (menu.path === '/system' || menu.parentId === 4 || menu.id === 4) {
      return true
    }
  }
  return false
}

// 判断是否是系统相关菜单
const isSystemRelatedMenu = (menu: any) => {
  // 系统管理本身
  if (menu.path === '/system' || menu.id === 4) return true
  // 系统管理的子菜单
  if (menu.parentId === 4) return true
  return false
}

// 判断是否是受保护的菜单
const isProtectedMenu = (menu: any) => {
  // 超级管理员的系统管理菜单
  if (menu.path === '/system' && selectedRole.value === 1) { // 假设超级管理员roleId为1
    return true
  }
  // 可以添加其他受保护的菜单判断
  return false
}

// 获取角色样式类名
const getRoleClass = (role: Role) => {
  switch (role.roleKey) {
    case 'superadmin':
      return 'role-superadmin'
    case 'admin':
      return 'role-admin'
    case 'counselor':
      return 'role-counselor'
    case 'student':
      return 'role-student'
    default:
      return ''
  }
}

// 处理标签页点击
const handleTabClick = (tab: any) => {
  const roleId = parseInt(tab.props.name)
  handleRoleChange(roleId)
}

// 获取角色列表
const loadRoles = async () => {
  try {
    const { data } = await getRoleList()
    // 根据当前用户角色过滤可见的角色列表
    const currentRole = store.state.user.role // 直接获取当前角色字符串
    
    if (currentRole === 'superadmin') {
      // 超级管理员可以看到所有角色
      roleList.value = data
    } else if (currentRole === 'admin') {
      // 管理员只能看到除超级管理员外的所有角色
      roleList.value = data.filter((role: Role) => role.roleKey !== 'superadmin')
    } else if (currentRole === 'counselor') {
      // 咨询师只能看到咨询师和学生角色
      roleList.value = data.filter((role: Role) => ['counselor', 'student'].includes(role.roleKey))
    } else {
      // 学生只能看到学生角色
      roleList.value = data.filter((role: Role) => role.roleKey === 'student')
    }
    
    // 设置默认选中角色
    if (roleList.value.length > 0) {
      const firstRole = roleList.value[0]
      activeTab.value = firstRole.id.toString()
      selectedRole.value = firstRole.id
      await handleRoleChange(firstRole.id)
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 获取菜单树
const loadMenuTree = async () => {
  try {
    const { data } = await getMenuTree()
    menuList.value = data
  } catch (error) {
    console.error('获取菜单树失败:', error)
  }
}

// 角色切换处理
const handleRoleChange = async (roleId: number) => {
  try {
    console.log('切换角色:', roleId)  // 添加日志
    selectedRole.value = roleId
    
    // 先获取菜单树
    const menuTreeRes = await getMenuTree()
    console.log('菜单树数据:', menuTreeRes)  // 添加日志
    
    if (menuTreeRes.data) {
      menuList.value = menuTreeRes.data
      
      // 再获取角色菜单
      const roleMenusRes = await getRoleMenus(roleId)
      console.log('角色菜单数据:', roleMenusRes)  // 添加日志
      
      if (roleMenusRes.data) {
        resetMenuChecked(menuList.value)
        setMenuChecked(menuList.value, roleMenusRes.data)
        
        if (isSuperAdmin(roleId)) {
          forceCheckSystemMenus(menuList.value)
        }
      }
    }
  } catch (error) {
    console.error('获取角色菜单失败:', error)
    ElMessage.error('获取菜单数据失败')
  }
}

// 重置菜单选中状态
const resetMenuChecked = (menus: any[]) => {
  menus.forEach(menu => {
    menu.checked = false
    if (menu.children?.length) {
      resetMenuChecked(menu.children)
    }
  })
}

// 设置菜单选中状态
const setMenuChecked = (menus: any[], checkedMenuIds: number[]) => {
  menus.forEach(menu => {
    menu.checked = checkedMenuIds.includes(menu.id)
    if (menu.children?.length) {
      setMenuChecked(menu.children, checkedMenuIds)
    }
  })
}

// 检查并更新父级菜单状态
const updateParentMenuStatus = (menus: any[], parentId: number) => {
  const parent = findMenuById(menus, parentId)
  if (parent) {
    // 获取所有子菜单的选中状态
    const checkedChildren = parent.children?.filter((child: any) => child.checked) || []
    // 如果没有选中的子菜单，则取消父级菜单的选中状态
    parent.checked = checkedChildren.length > 0
    // 如果父级还有父级，继续向上更新
    if (parent.parentId) {
      updateParentMenuStatus(menus, parent.parentId)
    }
  }
}

// 查找指定ID的菜单
const findMenuById = (menus: any[], id: number): any => {
  for (const menu of menus) {
    if (menu.id === id) {
      return menu
    }
    if (menu.children?.length) {
      const found = findMenuById(menu.children, id)
      if (found) return found
    }
  }
  return null
}

// 修改权限变更处理函数
const handlePermissionChange = (menu: any, checked: boolean) => {
  // 如果是系统管理相关菜单且是超级管理员角色，不允许修改
  if (selectedRole.value && isSuperAdmin(selectedRole.value) && isSystemRelatedMenu(menu)) {
    ElMessage.warning('系统管理菜单权限不允许修改')
    menu.checked = true
    return
  }

  // 更新当前菜单状态
  menu.checked = checked

  // 如果是父级菜单，同步更新所有子菜单
  if (menu.children?.length) {
    updateChildrenChecked(menu.children, checked)
  }
  
  // 如果是子菜单，检查并更新父级菜单状态
  if (menu.parentId) {
    updateParentMenuStatus(menuList.value, menu.parentId)
  }
}

// 更新子菜单选中状态
const updateChildrenChecked = (children: any[], checked: boolean) => {
  children.forEach(child => {
    // 如果不是禁用的菜单才更新状态
    if (!shouldDisableMenu(child)) {
      child.checked = checked
      if (child.children?.length) {
        updateChildrenChecked(child.children, checked)
      }
    }
  })
}

// 获取选中的菜单ID
const getCheckedMenuIds = (menus: any[]): number[] => {
  const ids: number[] = []
  menus.forEach(menu => {
    if (menu.checked) {
      ids.push(menu.id)
    }
    if (menu.children?.length) {
      ids.push(...getCheckedMenuIds(menu.children))
    }
  })
  return ids
}

// 保存修改
const handleSave = async () => {
  if (!selectedRole.value) {
    ElMessage.warning('请选择角色')
    return
  }

  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要保存修改吗？此操作将更新角色的菜单权限。',
      '确认保存',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    const menuIds = getCheckedMenuIds(menuList.value)
    await updateRoleMenus(selectedRole.value, menuIds)
    ElMessage.success('保存成功')
  } catch (error) {
    if (error !== 'cancel') {  // 不是取消操作才显示错误
      console.error('保存失败:', error)
      ElMessage.error('保存失败')
    }
  } finally {
    loading.value = false
  }
}

// 判断是否禁用复选框
const isDisabled = (menu: any) => {
  // 如果是超级管理员角色
  if (selectedRole.value === 1) {
    // 系统管理及其子菜单都禁用
    if (menu.path === '/system' || hasSystemParent(menu)) {
      return true
    }
  }
  return !canManageMenu(menu)
}

// 判断是否是系统管理的子菜单
const hasSystemParent = (menu: any) => {
  const findParent = (menus: any[], id: number): boolean => {
    for (const m of menus) {
      if (m.id === id) {
        return m.path === '/system'
      }
      if (m.children?.length) {
        const found = findParent(m.children, id)
        if (found) return true
      }
    }
    return false
  }
  return menu.parentId ? findParent(menuList.value, menu.parentId) : false
}

// 强制选中系统管理相关菜单
const forceCheckSystemMenus = (menus: any[]) => {
  menus.forEach(menu => {
    if (isSystemRelatedMenu(menu)) {
      menu.checked = true
    }
    if (menu.children?.length) {
      forceCheckSystemMenus(menu.children)
    }
  })
}

// 判断是否是有效的图标
const isValidIcon = (iconName: string) => {
  return iconName && typeof iconName === 'string' && Object.prototype.hasOwnProperty.call(ElementPlusIconsVue, iconName)
}

// 初始化加载
onMounted(async () => {
  try {
    console.log('开始初始化')
    await loadRoles() // 直接使用 loadRoles 函数，它已经包含了角色过滤逻辑
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('初始化失败')
  }
})
</script>

<style lang="scss" scoped>
.menu-permission {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .permission-card {
    .card-header {
      .title {
        font-size: 18px;
        font-weight: bold;
        color: #303133;
      }
    }

    .role-tabs {
      :deep(.el-tabs) {
        &.el-tabs--border-card {
          box-shadow: none;
          border: 1px solid #dcdfe6;
          
          > .el-tabs__header {
            background-color: #f5f7fa;
            border-bottom: 1px solid #dcdfe6;
            
            .el-tabs__item {
              height: 40px;
              line-height: 40px;
              font-size: 14px;
              color: #606266;
              
              &.is-active {
                color: #409eff;
                background-color: #fff;
                border-right: 1px solid #dcdfe6;
                border-left: 1px solid #dcdfe6;
              }
              
              &:not(.is-disabled):hover {
                color: #409eff;
              }
              
              &.is-disabled {
                color: #c0c4cc;
              }
            }
          }
          
          > .el-tabs__content {
            padding: 20px;
          }
        }
      }
    }

    .menu-table {
      margin: 0;
      
      :deep(.el-table) {
        .el-table__header {
          th {
            background-color: #f5f7fa;
            color: #606266;
            font-weight: bold;
            height: 50px;
            text-align: left !important;
          }
        }
        
        .el-table__body {
          td {
            height: 50px;
          }
        }
        
        .menu-cell {
          height: 50px;
          line-height: 50px;
          padding-left: 10px;
        }
      }
    }

    .action-bar {
      margin-top: 20px;
      text-align: center;
      
      .el-button {
        padding: 12px 30px;
        font-size: 14px;
      }
    }
  }
}

.role-tabs {
  :deep(.el-tabs) {
    .role-label {
      &.role-superadmin {
        color: #f56c6c;  // 超级管理员红色
      }
      
      &.role-admin {
        color: #409eff;  // 管理员蓝色
      }
      
      &.role-counselor {
        color: #67c23a;  // 咨询师绿色
      }
      
      &.role-student {
        color: #909399;  // 学生灰色
      }
    }
  }
}
</style> 